package objectCase;

public class StudentsTest {
    public static void main(String[] args) {
        Students[] students = new Students[3];
        students[0] = new Students("张三",18,1);
        students[1] = new Students("李四",20,2);
        students[2] = new Students("王五",22,3);

        Students stu4 = new Students("赵六",24,4);
        if(IdIsExist(students,stu4.getId())){
            System.out.println("该id已存在，修改后重新录入");
        }else {
            if(checkLength(students) < students.length){
                students[checkLength(students)] = stu4;
                printStudents(students);
            }else {
                Students[] newStuArray = newArrayReturn(students,stu4);
                printStudents(newStuArray);
            }
        }

    }
    /*
     * 打印学生信息
     * @param students
     */
    public static void printStudents(Students[] students) {
        for (Students student : students) {
            System.out.println("姓名：" + student.getName() + " 年龄：" + student.getAge() + " id：" + student.getId());
        }

    }
    public static  void  deleteStudent(Students[] students, int id) {
        int count = checkLength(students);
        if(IdIsExist(students,id)){
            for (int i = 0; i < count; i++) {
                if (students[i].getId() == id) {
                    for (int j = i; j < count - 1; j++) {
                        students[j] = students[j + 1];
                    }
                    students[count - 1] = null;
                    break;
                }
            }
        } else {
            System.out.println("删除失败");
        }
    }
    /*
     * 数组扩容
     * @param students
     * @param student
     * @return
     */
    public static Students[] newArrayReturn(Students[] students,Students student) {
        Students[] newStudents = new Students[students.length + 1];
        for (int i = 0; i < students.length; i++) {
            newStudents[i] = students[i];
        }
        newStudents[newStudents.length - 1] = student;
        return newStudents;

    }
    /*
     * 检查数组长度
     * @param students
     * @return
     */
    public static int checkLength(Students[] students) {
        int count = 0;
        for (Students student : students) {
            if (student != null) {
                count++;
            }
        }
        return count;
    }
    /*
     * 判断id是否存在
     * @param students
     * @param id
     * @return
     */
    public static boolean IdIsExist(Students[] students, int id) {
        int count = checkLength(students);
        int[] idList = new int[students.length];
        for (int i = 0; i < count; i++) {
            idList[i] = students[i].getId();
        }
        boolean flag = false;
        for (int j : idList) {
            if (j == id) {
                flag = true;
                break;
            }
        }
        return flag;
    }
}
